package com.example.dog.core.threads;

import com.example.dog.core.actions.*;
import com.example.dog.core.entity.Dog;
import com.example.dog.core.service.DogService;
import com.example.dog.core.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public class DogRunTread extends Thread {
    private DogService dogService;
    private Dog dog;
    public DogRunTread(){
        dogService = SpringContextHolder.getBean(DogService.class);
    }
    @Override
    public void run() {
        log.info("程序开始启动+++++++++++");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            dog = dogService.getById(2);
            while (true) {
                log.info("当前时间：" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                Behavior behavior = executeBehavior(dog.getBehaviors());
                if(behavior == null){
                    log.error("获取不到当前行为");
                    continue;
                }
                behavior.execute(dog.getName());
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }

    private static Behavior executeBehavior(Behavior[] behaviors) {
        Behavior behavior = null;
        for(int i=0;i<behaviors.length;i++){
            if(behaviors[i] instanceof EatBehavior && ((EatBehavior)behaviors[i]).getTired() >2){
                behavior = behaviors[i];
                break;
            }
            if(behaviors[i] instanceof SleepBehavior && ((SleepBehavior)behaviors[i]).getTired() >2){
                behavior = behaviors[i];
                break;
            }
            if(behaviors[i] instanceof PlayBehavior && ((PlayBehavior)behaviors[i]).getTired() >2){
                behavior = behaviors[i];
                break;
            }
            if(behaviors[i] instanceof ThinkBehavior && ((ThinkBehavior)behaviors[i]).getTired() >2){
                behavior = behaviors[i];
                break;
            }
        }
        return behavior;
    }
}
